from django.http import JsonResponse
from lib.common import AbstractHandler, get_api_result
from apps.student.share import app_logger
from services.datamodel.absorbed.models import (mm_Note, mm_NoteLike, mm_NoteMessage, mm_FamousSentences,
                                                mm_ShareParameter, mm_AllData, mm_NoteServersMessage,
                                                mm_NoteWechatMessage, mm_NoteBanner,
                                                mm_Plan, mm_PlanCourse, mm_PlanStage, mm_PlanStageCourse, mm_PlanJoinInfo, mm_PlanClockInInfo)
from services.datamodel.student.models import mm_Student
import json
from django.core.cache import cache
from django.db import transaction
from django.forms.models import model_to_dict

class AbsorbedHandler(AbstractHandler):
    def __init__(self):
        AbstractHandler.__init__(self, app_logger)
        self.app_logger = app_logger
        self.METHOD_TAB = {
            'POST': {
                'del_note': self.del_note,
                'del_note_message':self.del_note_message,
                'del_famous_sentences': self.del_famous_sentences,
                'create_famous_sentences': self.create_famous_sentences,
                'create_share_parameter': self.create_share_parameter,
                'update_famous_sentences': self.update_famous_sentences,
                'create_server_message': self.create_server_message,
                'update_server_message': self.update_server_message,
                'update_status': self.update_status,
                'create_banner': self.create_banner,
                'update_banner': self.update_banner,
                'delete_banner': self.delete_banner,
                'update_share_parameter': self.update_share_parameter,
                'delete_share_parameter': self.delete_share_parameter,
                'change_plan_status': self.change_plan_status,
                'create_plan': self.create_plan,
                'update_plan': self.update_plan,
                'create_plan_course': self.create_plan_course,
                'update_plan_course': self.update_plan_course,
                'create_plan_stage': self.create_plan_stage,
                'update_plan_stage': self.update_plan_stage,
                'update_plan_task': self.update_plan_task,
                'del_plan_task': self.del_plan_task,
                'update_plan_task_refine': self.update_plan_task_refine,
            },
            'GET': {
                'get_note_list': self.get_note_list,
                'get_note': self.get_note,
                'note_message': self.note_message,
                'data_analysis': self.data_analysis,
                'analysis_basics': self.analysis_basics,
                'famous_sentences': self.famous_sentences,
                'get_user': self.get_user,
                'user_detail': self.user_detail,
                'get_famous_sentences': self.get_famous_sentences,
                'get_servers_message': self.get_servers_message,
                'get_servers_detail': self.get_servers_detail,
                'get_wechat_t': self.get_wechat_t,
                'get_category': self.getCategory,
                'banner_list': self.banner_list,
                'get_banner': self.get_banner,
                'get_share_parameter': self.get_share_parameter,
                'get_parameter_list': self.get_parameter_list,
                'get_plan_list': self.get_plan_list,
                'get_plan': self.get_plan,
                'get_plan_course_list': self.get_plan_course_list,
                'get_plan_course': self.get_plan_course,
                'get_plan_stage_list': self.get_plan_stage_list,
                'get_plan_stage_student_list': self.get_plan_stage_student_list,
                'get_plan_stage': self.get_plan_stage,
                'get_plan_stage_task_list': self.get_plan_stage_task_list,
            }
        }

    def get_user(self, request):
        page = request.GET.get('page', 1)
        nickname = request.GET.get('nickname', '')
        phone = request.GET.get('phone', '')
        identity = request.GET.get('identity', '')
        start_date = request.GET.get('start_date', '')
        end_date = request.GET.get('end_date', '')
        duration_sum_sort = request.GET.get('duration_sum_sort', '')
        last_day_sort = request.GET.get('last_day_sort', '')
        export = request.GET.get('export', 0)
        num = request.GET.get('num', 50)
        if export:
            return mm_Student.get_student_list(page=page, nickname=nickname, phone=phone, identity=identity, start_date=start_date,
                                               end_date=end_date, export=export, source=13)
        res = mm_Student.get_student_list(page=page, nickname=nickname, phone=phone, identity=identity, start_date=start_date,
                                          end_date=end_date, num=num, source=13, duration_sum_sort=duration_sum_sort, last_day_sort=last_day_sort)
        return self.success(res)

    def get_note_list(self, request):
        page = request.GET.get('page', 1)
        nickname = request.GET.get('nickname', '')
        types = request.GET.get('types', '')
        types_sort = request.GET.get('types_sort', '')
        pv_sort = request.GET.get('pv_sort', '')
        share_sort = request.GET.get('share_sort', '')
        message_sort = request.GET.get('message_sort', '')
        like_sort = request.GET.get('like_sort', '')
        status_sort = request.GET.get('status_sort', '')
        start_date = request.GET.get('start_date', '')
        end_date = request.GET.get('end_date', '')
        status = request.GET.get('status', '')
        num = request.GET.get('num', 50)
        export = request.GET.get('export', 0)
        if export:
            return mm_Note.get_list(page=page, num=num, nickname=nickname, types=types, start_date=start_date,
                                    end_date=end_date, status=status, export=export)
        res = mm_Note.get_list(page=page, num=num, nickname=nickname, types=types, start_date=start_date,
                               end_date=end_date, status=status, types_sort=types_sort, pv_sort=pv_sort, share_sort=share_sort,
                               message_sort=message_sort, like_sort=like_sort, status_sort=status_sort)
        return self.success(res)

    def user_detail(self, request):
        id = request.GET.get('id', 0)
        user = mm_Student.filter(id=id).values().first()
        top_arr, dict_sorted_re = mm_Student.user_answer(user_id=id)
        user['top_arr'] = top_arr
        user['dict_sorted_re'] = dict_sorted_re
        return self.success(user)

    def get_note(self, request):
        id = request.GET.get('id', 0)
        res = mm_Note.filter(id=id).values("content", "created_at", "like", "share", "message", "private", "status", "duration",
                             "student__nick_name", "student__id", "id", "student__avatar", "imgs",
                             "types", "student__title").first()
        return self.success(res)

    def del_note(self, request):
        id = request.POST.get('id', 0)
        mm_Note.filter(id=id).delete()
        return self.success()

    def note_message(self, request):
        page = request.GET.get('page', 1)
        nickname = request.GET.get('nickname', '')
        user_id = request.GET.get('user_id', 0)
        num = request.GET.get('num', 50)
        res = mm_NoteMessage.get_list(page=page, num=num, nickname=nickname, user_id=user_id, times=0, like=0)
        return self.success(res)

    def del_note_message(self, request):
        id = request.POST.get('id', 0)
        ids = json.loads(id)
        mm_NoteMessage.filter(id__in=ids).delete()
        return self.success()

    def famous_sentences(self, request):
        page = request.GET.get('page', 1)
        num = request.GET.get('num', 50)
        res = mm_FamousSentences.get_list(page=page, num=num)
        return self.success(res)

    def del_famous_sentences(self, request):
        id = request.POST.get('id', 0)
        mm_FamousSentences.filter(id=id).delete()
        return self.success()

    def create_famous_sentences(self, request):
        content_one = request.POST.get('content_one', '')
        content_two = request.POST.get('content_two', '')
        name = request.POST.get('name', '')
        mm_FamousSentences.create(content_one=content_one, content_two=content_two, name=name)
        return self.success()

    def update_famous_sentences(self, request):
        id = request.POST.get('id', '')
        content_one = request.POST.get('content_one', '')
        content_two = request.POST.get('content_two', '')
        name = request.POST.get('name', '')
        mm_FamousSentences.filter(id=id).update(content_one=content_one, content_two=content_two, name=name)
        return self.success()

    def get_famous_sentences(self, request):
        id = request.GET.get('id', 0)
        res = mm_FamousSentences.filter(id=id).values().first()
        return self.success(res)

    def create_share_parameter(self, request):
        content = request.POST.get('content', '')
        content = json.loads(content)
        for v in content:
            mm_ShareParameter.create(title=v['title'], img=v['img'])
        return self.success()

    def data_analysis(self, request):
        page = request.GET.get('page', 1)
        num = request.GET.get('num', 50)
        start_date = request.GET.get('start_date', '')
        end_date = request.GET.get('end_date', '')
        export = request.GET.get('export', 0)
        if export:
            return mm_AllData.get_list(page=page, num=num, start_date=start_date, end_date=end_date, export=export)
        res = mm_AllData.get_list(page=page, num=num, start_date=start_date, end_date=end_date)
        return self.success(res)

    def analysis_basics(self, request):
        page = request.GET.get('page', 1)
        num = request.GET.get('num', 50)
        start_date = request.GET.get('start_date', '')
        end_date = request.GET.get('end_date', '')
        export = request.GET.get('export', 0)
        if export:
            return mm_AllData.basics_analysis(page=page, num=num, start_date=start_date, end_date=end_date, export=export)
        res = mm_AllData.basics_analysis(page=page, num=num, start_date=start_date, end_date=end_date)
        return self.success(res)

    def get_servers_message(self, request):
        page = request.GET.get('page', 1)
        num = request.GET.get('num', 50)
        res = mm_NoteServersMessage.get_list(page=page, num=num)
        return self.success(res)

    def create_server_message(self, request):
        title = request.POST.get('title', '')
        tmpl_id = request.POST.get('tmpl_id', '')
        rule = request.POST.get('rule', 1)
        activity = request.POST.get('times', '')
        # explain = request.POST.get('explain', '')
        datas = request.POST.get('datas', '')
        res = mm_NoteServersMessage.create(title=title, tmpl_id=tmpl_id, rule=rule, explain=datas, activity=activity)
        # 创建缓存服务
        resObj = mm_NoteWechatMessage.get_or_default(id=tmpl_id)
        cache_data = {'content': datas, 'id': res.id, 'tid': resObj.priTmplId, 'status': 1, 'times': activity, 'rule':int(rule)}
        cache.set('w_message_'+str(res.id), json.dumps(cache_data), None)
        return self.success()

    def get_servers_detail(self, request):
        id = request.GET.get('id', 1)
        res = mm_NoteServersMessage.filter(id=id).values().first()
        return self.success(res)

    def update_server_message(self, request):
        title = request.POST.get('title', '')
        id = request.POST.get('id', '')
        tmpl_id = request.POST.get('tmpl_id', '')
        rule = request.POST.get('rule', 1)
        datas = request.POST.get('datas', '')
        activity = request.POST.get('times', '')
        mm_NoteServersMessage.filter(id=id).update(title=title, tmpl_id=tmpl_id, rule=rule, explain=datas, activity=activity)
        resObj = mm_NoteWechatMessage.get_or_default(id=tmpl_id)
        cache_data = {'content': datas, 'id': id, 'tid': resObj.priTmplId, 'status': 1, 'times': activity, 'rule': int(rule)}
        cache.set('w_message_'+str(id), json.dumps(cache_data), None)
        return self.success()

    def update_status(self, request):
        id = request.POST.get('id', '')
        status = request.POST.get('status', 0)
        if status == "0":
            status = 2
        mm_NoteServersMessage.filter(id=id).update(status=status)
        j_cache_data = cache.get('w_message_'+str(id))
        if j_cache_data:
            cache_data = json.loads(j_cache_data)
            cache_data['status'] = status
            cache.set('w_message_'+str(id), json.dumps(cache_data), None)
        return self.success()

    def get_wechat_t(self, request):
        import collections
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(
            "wx3af648c742d8be80", "37829be2b13040fcc425b4dfd667092f"
        )
        retObj = get_api_result(url)
        if retObj.get('errcode'):
            self.app_logger.error(str(retObj))
            return self.error("微信服务器错误")
        access_token = retObj.get('access_token', None)
        url = "https://api.weixin.qq.com/wxaapi/newtmpl/gettemplate?access_token={}".format(access_token)
        Obj = get_api_result(url)
        import re
        for v in Obj['data']:
            data_name = collections.defaultdict(list)
            new3_list = v['content'].split("\n")
            for v1 in new3_list:
                title = v1[0:v1.rfind(':')]
                res = re.findall(r'{{([^"]+)}}', v1)
                if res:
                    data_name[str(res[0][:-5])].append(title)
            mm_NoteWechatMessage.update_or_create(priTmplId=v['priTmplId'], defaults={'title': v['title'],
                                                                                      'content': json.dumps(data_name),
                                                                                      'example': v['example'],
                                                                                      'types': v['type'],
                                                                                      'keywordEnumValueList': json.dumps(v['keywordEnumValueList'])})
        res = mm_NoteWechatMessage.values('id', 'title', 'content')
        for v in res:
            v['content'] = json.loads(v['content'])
        return self.success(list(res))

    def getCategory(self, request):
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(
            "wx3af648c742d8be80", "37829be2b13040fcc425b4dfd667092f"
        )
        retObj = get_api_result(url)
        if retObj.get('errcode'):
            self.app_logger.error(str(retObj))
            return self.error("微信服务器错误")
        access_token = retObj.get('access_token', None)
        url = "https://api.weixin.qq.com/wxaapi/newtmpl/getcategory?access_token={}".format(access_token)
        Obj = get_api_result(url)
        ids = []
        for v in Obj['data']:
            ids.append(str(v['id']))
        str_id = ','.join(ids)
        PubTemplate = "https://api.weixin.qq.com/wxaapi/newtmpl/getpubtemplatetitles?access_token={}&ids={}&start=0&limit=30".format(access_token, str_id)
        getPubTemplateTitleList = get_api_result(PubTemplate)
        return self.success(getPubTemplateTitleList['data'])

    def banner_list(self, request):
        page = request.GET.get('page', 1)
        num = request.GET.get('num', 10)
        res = mm_NoteBanner.get_list(page=page, num=num)
        return self.success(res)

    def create_banner(self, request):
        name = request.POST.get('name', '')
        img = request.POST.get('img', '')
        sort = request.POST.get('sort', 0)
        url = request.POST.get('url', '')
        num = mm_NoteBanner.count()
        if num >= 3:
            return self.error("最多存在3个banner")
        mm_NoteBanner.create(name=name, img=img, sort=sort, url=url)
        return self.success()

    def get_banner(self, request):
        id = request.GET.get('id', 0)
        res = mm_NoteBanner.filter(id=id).values().first()
        return self.success(res)

    def update_banner(self, request):
        id = request.POST.get('id', 0)
        name = request.POST.get('name', '')
        img = request.POST.get('img', '')
        sort = request.POST.get('sort', 0)
        url = request.POST.get('url', '')
        mm_NoteBanner.filter(id=id).update(name=name, img=img, sort=sort, url=url)
        return self.success()

    def delete_banner(self, request):
        id = request.POST.get('id', 0)
        mm_NoteBanner.filter(id=id).delete()
        return self.success()

    def get_share_parameter(self, request):
        id = request.GET.get('id', 0)
        res = mm_ShareParameter.filter(id=id).values().first()
        return self.success(res)

    def update_share_parameter(self, request):
        id = request.POST.get('id', 0)
        title = request.POST.get('title', '')
        img = request.POST.get('img', '')
        mm_ShareParameter.filter(id=id).update(title=title, img=img)
        return self.success()

    def delete_share_parameter(self, request):
        id = request.POST.get('id', 0)
        mm_ShareParameter.filter(id=id).delete()
        return self.success()

    def get_parameter_list(self, request):
        page = request.GET.get('page', 1)
        num = request.GET.get('num', 10)
        res = mm_ShareParameter.get_list(page=page, num=num)
        return self.success(res)

    # plan
    def get_plan_list(self, request):
        page = request.GET.get('page', 1)
        title = request.GET.get('title', '')
        start_date = request.GET.get('start_date', '')
        end_date = request.GET.get('end_date', '')
        status = request.GET.get('status', '')
        num = request.GET.get('num', 50)
        export = request.GET.get('export', 0)
        if export:
            return mm_Plan.get_list(page=page, num=num, title=title, start_date=start_date,
                                    end_date=end_date, status=status, export=export)
        res = mm_Plan.get_list(page=page, num=num, title=title, start_date=start_date,
                               end_date=end_date, status=status)
        return self.success(res)

    def get_plan(self, request):
        id = request.GET.get('id', 0)
        res = mm_Plan.filter(id=id).values().first()
        return self.success(res)

    def change_plan_status(self, request):
        id = request.POST.get('id', '')
        status = request.POST.get('status', 0)
        if int(status) not in [0, 1]:
            return self.error("计划状态不存在！")
        mm_Plan.filter(id=id).update(status=status)
        return self.success()

    def create_plan(self, request):
        content = request.POST.get('content', '')
        content = json.loads(content)
        for v in content:
            mm_Plan.create(code=v['code'], content=v['content'], cycle=v['cycle'],
                                 desc=v['desc'], drainage_desc=v['drainage_desc'], img=v['img'], bg_img=v['bg_img'],
                                 original_price=v['original_price'], price=v['price'], replenish=v['replenish'],
                                 title=v['title'], virtual_num=v['virtual_num'])
        return self.success()

    def update_plan(self, request):
        id = request.POST.get('id', 0)
        code = request.POST.get('code', '')
        content = request.POST.get('content', '')
        cycle = request.POST.get('cycle', '')
        desc = request.POST.get('desc', '')
        drainage_desc = request.POST.get('drainage_desc', '')
        img = request.POST.get('img', '')
        bg_img = request.POST.get('bg_img', '')
        original_price = request.POST.get('original_price', '')
        price = request.POST.get('price', '')
        replenish = request.POST.get('replenish', '')
        title = request.POST.get('title', '')
        virtual_num = request.POST.get('virtual_num', '')
        mm_Plan.filter(id=id).update(code=code, content=content, cycle=cycle,
                                           desc=desc, drainage_desc=drainage_desc, img=img, bg_img=bg_img,
                                           original_price=original_price, price=price, replenish=replenish,
                                           title=title, virtual_num=virtual_num)
        return self.success()

    # plan_course
    def get_plan_course_list(self, request):
        page = request.GET.get('page', 1)
        num = request.GET.get('num', 50)
        plan_id = request.GET.get('plan_id', '')
        title = request.GET.get('title', '')
        start_date = request.GET.get('start_date', '')
        end_date = request.GET.get('end_date', '')
        res = mm_PlanCourse.get_list(page=page, num=num, plan_id=plan_id, title=title, start_date=start_date,
                               end_date=end_date)
        return self.success(res)

    def get_plan_course(self, request):
        id = request.GET.get('id', 0)
        res = mm_PlanCourse.filter(id=id).values().first()
        return self.success(res)

    def create_plan_course(self, request):
        content = request.POST.get('content', '')
        content = json.loads(content)
        for v in content:
            mm_PlanCourse.create(plan_id=v['plan_id'], title=v['title'], desc=v['desc'], content=v['content'], task=v['task'])
        return self.success()

    def update_plan_course(self, request):
        id = request.POST.get('id', 0)
        plan_id = request.POST.get('plan_id', '')
        title = request.POST.get('title', '')
        desc = request.POST.get('desc', '')
        content = request.POST.get('content', '')
        task = request.POST.get('task', '')
        mm_PlanCourse.filter(id=id, plan_id=plan_id).update(title=title, desc=desc, content=content, task=task)
        return self.success()

    # plan_stage
    def get_plan_stage_list(self, request):
        page = request.GET.get('page', 1)
        num = request.GET.get('num', 50)
        plan_id = request.GET.get('plan_id', '')
        desc = request.GET.get('desc', '')
        start_date = request.GET.get('start_date', '')
        end_date = request.GET.get('end_date', '')
        res = mm_PlanStage.get_list(page=page, num=num, plan_id=plan_id, desc=desc, start_date=start_date,
                               end_date=end_date)
        return self.success(res)

    def get_plan_stage(self, request):
        id = request.GET.get('id', 0)
        planStage = mm_PlanStage.get(id=id)
        planStageCourse = planStage.plan_stage_course_ps.all().order_by("day").values("id", "plan_course_id", "day",)
        res = model_to_dict(planStage)
        res['stage_course'] = list(planStageCourse)
        return self.success(res)

    def create_plan_stage(self, request):
        content = request.POST.get('content', '')
        content = json.loads(content)
        try:
            with transaction.atomic():
                for v in content:
                    planStage = mm_PlanStage.create(plan_id=v['plan_id'], desc=v['desc'])
                    all_dates = []
                    if planStage and v['themes']:
                        for theme in v['themes']:
                            all_dates.append(theme['day'])
                            planStage.plan_stage_course_ps.create(plan_id=planStage.plan_id, plan_stage=planStage,
                                                      plan_course_id=theme['plan_course_id'], day=theme['day'])
                    planStage.all_dates = json.dumps(all_dates)
                    if all_dates:
                        planStage.start_day = min(all_dates)
                        planStage.end_day = max(all_dates)
                    lastPlanStage = mm_PlanStage.filter(plan_id=v['plan_id']).exclude(id=planStage.id).last()
                    counter = 1 if lastPlanStage is None else lastPlanStage.counter + 1
                    print(lastPlanStage, counter)
                    planStage.save()
        except Exception as e:
            print(e)
            return self.error('server error')

        return self.success()

    def update_plan_stage(self, request):
        id = request.POST.get('id', 0)
        plan_id = request.POST.get('plan_id', '')
        desc = request.POST.get('desc', '')
        themes = request.POST.get('themes', '')
        themes = json.loads(themes)
        try:
            with transaction.atomic():
                mm_PlanStage.filter(id=id, plan_id=plan_id).update(desc=desc)
                if themes:
                    for theme in themes:
                        mm_PlanStageCourse.filter(id=theme['id'], day=theme['day']).update(plan_course_id=theme['plan_course_id'])
        except Exception as e:
            print(e)
            return self.error('server error')

        return self.success()

    # plan_join_info
    def get_plan_stage_student_list(self, request):
        page = request.GET.get('page', 1)
        num = request.GET.get('num', 50)
        plan_stage_id = request.GET.get('plan_stage_id', '')
        phone = request.GET.get('phone', '')
        nickname = request.GET.get('nickname', '')
        start_date = request.GET.get('start_date', '')
        end_date = request.GET.get('end_date', '')
        export = request.GET.get('export', 0)
        if export:
            return mm_PlanJoinInfo.get_list(page=page, num=num, plan_stage_id=plan_stage_id, phone=phone, nickname=nickname, start_date=start_date,
                               end_date=end_date, export=export)
        res = mm_PlanJoinInfo.get_list(page=page, num=num, plan_stage_id=plan_stage_id, phone=phone, nickname=nickname, start_date=start_date,
                               end_date=end_date, export=export)
        return self.success(res)

    # plan_clock_in_info
    def get_plan_stage_task_list(self, request):
        page = request.GET.get('page', 1)
        num = request.GET.get('num', 50)
        plan_id = request.GET.get('plan_id', '')
        plan_stage_id = request.GET.get('plan_stage_id', '')
        phone = request.GET.get('phone', '')
        nickname = request.GET.get('nickname', '')
        course_title = request.GET.get('course_title', '')
        start_date = request.GET.get('start_date', '')
        end_date = request.GET.get('end_date', '')
        export = request.GET.get('export', 0)
        if export:
            return mm_PlanClockInInfo.get_list(page=page, num=num, plan_id=plan_id, plan_stage_id=plan_stage_id, phone=phone, nickname=nickname,
                                            course_title=course_title, start_date=start_date, end_date=end_date, export=export)
        res = mm_PlanClockInInfo.get_list(page=page, num=num, plan_id=plan_id, plan_stage_id=plan_stage_id, phone=phone, nickname=nickname,
                                       course_title=course_title, start_date=start_date, end_date=end_date, export=export)
        return self.success(res)

    def update_plan_task(self, request):
        id = request.POST.get('id', 0)
        types = request.POST.get('types', 2)
        content = request.POST.get('content', '')
        imgs = request.POST.get('imgs', '')
        mm_Note.filter(id=id, types=types).update(content=content, imgs=imgs)
        return self.success()

    def del_plan_task(self, request):
        id = request.POST.get('id', 0)
        task = mm_PlanClockInInfo.get(id=id)
        task.note.delete()
        return self.success()

    def update_plan_task_refine(self, request):
        id = request.POST.get('id', 0)
        task = mm_PlanClockInInfo.get(id=id)
        refine = task.refine
        plan_id = task.plan_id
        if int(refine):
            task.refine = 0
            task.save()
        else:
            refine_count = mm_PlanClockInInfo.filter(plan_id=plan_id).count()
            if refine_count >= 10:
                return self.error('已达上限，需取消1条后，才能继续添加')
            else:
                task.refine = 1
                task.save()
        return self.success()

handler = AbsorbedHandler()
